<?php

class m_users extends CI_Model{
	
	function _list($data){
		extract($data);
		$sql = "SELECT 
					user_name,
					user_passwd,
					user_log,
					s_groups_id,
					groups_name,
					user_id
				FROM s_users
					LEFT JOIN s_groups ON groups_id = s_groups_id
				WHERE 
					user_active = 'y'
		";
		
		if (@$user_name != "") $sql .= " AND user_name like '%".@$user_name."%'";
		if (@$groups_name != "") $sql .= " AND groups_name like '%".@$groups_name."%'";
		if (@$staff_name != "") $sql .= " AND staff_name like '%".@$staff_name."%'";
		
		$query = $this->db->query($sql);
		$records = $query->num_rows();
		
		$sql = "SELECT * FROM (".$sql.") k LIMIT ".(($page - 1) * $rows)." , ".$rows;
		$query = $this->db->query($sql);
		$result = $query->result();
		
		return '{ 
		  "total": "'.ceil($records / $rows).'", 
		  "page": "'.$page.'", 
		  "records": "'.$records .'",
		  "rows" : '.json_encode($result).'
		}';
	}
	
	function _insert($data){
		$this->db->insert('s_users',$data);
		return 1;
	}
	
	function _update($data,$id){
		$this->db->where('user_id',$id);
		$this->db->update('s_users',$data);
		return 1;
	}
	
	function _delete($data,$id){
		$this->db->where('user_id',$id);
		$this->db->update('s_users',$data);
		return 1;
	}
	
	function s_groups(){
		$sql = "SELECT groups_id, groups_name FROM s_groups WHERE groups_active = 1";
		$query = $this->db->query($sql);
		$data = array("");
		foreach($query->result() as $row){
			$data[$row->groups_id] = $row->groups_name;
		}
		return $data;
	}
	function m_staff_id(){
		$sql = "SELECT staff_name, staff_id FROM m_staff WHERE staff_active = 1";
		$query = $this->db->query($sql);
		$data = array("");
		foreach($query->result() as $row){
			$data[$row->staff_id] = $row->staff_name;
		}
		return $data;
	}
	
	function _check_staff_uid($uid){
		$sql = "SELECT staff_id FROM m_staff WHERE staff_uid = '".$uid."'";
		$query = $this->db->query($sql);
		if ($query->num_rows() > 0){
			return $query->row("staff_id");
		}else{
			$cn = $this->ldap->cari_staff_name($uid);
			$data = array(
				"staff_uid" => $uid,
				"staff_name" => $cn
			);
			$this->db->insert("m_staff",$data);
			return $this->db->insert_id();
		}
	}
}